// vp_cai/pages/index/areas.js
var app = getApp();
var vp = require('../../resource/js/vp.js');
Page({
  data: {
    isEditing: false,
	isSelf:0,
    currentDate: "",
    userInfo: {
      name: '',
      gender: 1,
	  genderName:'男',
      relation: '',
      birth: '',
      height: '',
      weight: '',
	  health_tips:'健康生活每一天',
      blood_types: 'A',
	  bloodTypeName:'A型',
	  nickName:'',
	  phone:'',
	  avatarUrl:'',
    },
    relations: [
      { name: '爸爸', value: '爸爸' },
      { name: '妈妈', value: '妈妈' },
      { name: '老公', value: '老公' },
      { name: '老婆', value: '老婆' },
      { name: '儿子', value: '儿子' },
      { name: '女儿', value: '女儿' },
      { name: '爷爷', value: '爷爷' },
      { name: '奶奶', value: '奶奶' },
      { name: '外公', value: '外公' },
      { name: '外婆', value: '外婆' },
      { name: '其他', value: '其他' },
    ],
    genders: [
      { name: '男', value: '1' },
      { name: '女', value: '2' },
      { name: '其他', value: '3' }
    ],
    bloodTypes: [
      { name: 'A型', value: 'A' },
      { name: 'B型', value: 'B' },
      { name: 'AB型', value: 'AB' },
      { name: 'O型', value: 'O' }
    ],
    genderIndex: 0,
    relationIndex: 0,
    bloodTypeIndex: 0
  },
  onShow:function(){
	  let can_edit_baseinfo = wx.getStorageSync('can_edit_baseinfo')
	  this.setData({
	    isEditing: can_edit_baseinfo
	  });
  },
  onLoad: function(options) {
	 let is_edit = options.is_edit
	  this.setData({
	    isEditing: is_edit
	  });
	 let is_self = options.is_self
	 let activeUser = wx.getStorageSync('activeUser')
	 if(activeUser && activeUser.id > 0){
	 	is_self = activeUser.is_self
	 }
	 // 初始化选择器索引
	 this.setData({
	 	isSelf:is_self,
		userInfo:activeUser,
	 	currentDate:this.getCurrentDateString(),
	 	genderIndex: this.data.genders.findIndex(item => item.value === this.data.userInfo.gender),
	 	bloodTypeIndex: this.data.bloodTypes.findIndex(item => item.value === this.data.userInfo.blood_types)
	 });
  },
// 新增方法：获取当前日期字符串
  getCurrentDateString: function() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  // 开始编辑
  startEditing: function() {
    this.setData({
      isEditing: true
    });
  },

  // 取消编辑
  cancelEditing: function() {
    wx.showModal({
      title: '确认取消',
      content: '您确定要放弃已修改的内容吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            isEditing: false
          });
		  if(this.data.isSelf == 1){
			wx.redirectTo({
				url: '/vp_pz/pages/user/index'
			});
		  }else{
			  wx.redirectTo({
			  	url: '/vp_pz/pages/familydoctor/index'
			  });
		  }
        }
      }
    });
  },
  // 保存信息
  saveInfo: function() {
	const that = this;
    // 这里可以添加表单验证逻辑
    if (!this.data.userInfo.name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    
    if(this.data.isSelf == 1){
    	this.data.userInfo.relation = '本人'
    }
    if (!this.data.userInfo.relation) {
      wx.showToast({
        title: '请选择成员关系',
        icon: 'none'
      });
      return;
    }
	if(!this.data.userInfo.health_tips){
		this.data.userInfo.health_tips = '健康生活每一天'
	}
    // 模拟保存操作
    wx.showLoading({
      title: '保存中...',
    });
    let jsonData = JSON.stringify(this.data.userInfo);
    app.util.request({
    	url: 'Familydoctor/createData',
    	data: jsonData,
    	method:'POST',
    	headers: {
    		'Content-Type': 'application/json',
    	},
    	success(res) {
    		console.log(res)
    		if(res.data.code){	
				wx.hideLoading();
				wx.showToast({
				  title: '保存成功',
				  icon: 'success'
				});
				that.setData({
				  isEditing: false
				});
				wx.setStorageSync('activeUser',res.data.data)
				wx.setStorageSync('create_data',1)
				setTimeout(() => {
				  wx.navigateBack();
				}, 500);
    		}else{
    			wx.showToast({ title: '提交失败请重试' });
    		}
    	}
    })
  },
  onNameChange:function(e){
	this.setData({ 'userInfo.name': e.detail.value })
  },
  onHeightChange:function(e){
	this.setData({ 'userInfo.height': e.detail.value })
  },
  onWeightChange:function(e){
	this.setData({ 'userInfo.weight': e.detail.value })
  },
  onHealthtipChange:function(e){
	  this.setData({ 'userInfo.healthtips': e.detail.value })
  },
  // 改变成员管理
  changeRelation: function(e) {
    let index = e.detail.value || 0;
	if(index < 0 || index == undefined) index = 0;
    this.setData({
      relationIndex: index,
      'userInfo.relation': this.data.relations[index].name
    });
  },
  // 改变性别
  changeGender: function(e) {
    let index = e.detail.value || 0;
	
	if(index < 0 || index == undefined) index = 0;
		  console.log('index:',index)
    this.setData({
      genderIndex: index,
      'userInfo.gender': this.data.genders[index].value,
      'userInfo.genderName': this.data.genders[index].name,
    });
  },

  // 改变出生日期
  changeBirthday: function(e) {
	  console.log('e.detail.value:',e.detail.value)
    this.setData({
      'userInfo.birth': e.detail.value
    });
  },

  // 改变血型
  changeBloodType: function(e) {
    let index = e.detail.value || 0;
	
	if(index < 0 || index == undefined) index = 0;
    this.setData({
      bloodTypeIndex: index,
      'userInfo.blood_types': this.data.bloodTypes[index].value,
      'userInfo.bloodTypeName': this.data.bloodTypes[index].name
    });
  },
// 获取用户信息
		  getUserInfo() {
		    const self = this;
			
			wx.getUserProfile({
			  desc: '用于完善会员资料', // 声明用途
			  success: (res) => {
				this.setData({
				  'userInfo.gender': res.userInfo.gender
				})
			  },
			  fail: (err) => {
				console.error('获取失败:', err)
				wx.showToast({
				  title: '获取用户信息失败',
				  icon: 'none'
				})
			  }
			})
			  wx.login({
			    success: (loginRes) => {
					console.log(loginRes)
			      if (loginRes.code) {
			        // 发送登录code到服务器获取session_key
			        app.util.request({
			          url: 'User/gowxLogin',
			          method: 'POST',
			          data: { code: loginRes.code },
			          success: (res) => {
			            self.setData({ showuserModal: true })
			          }
			        })
			      }
			    }
			  })
		    
		  },
		  // 获取微信头像
		handleChooseAvatar(e) {
				try {
				    if (typeof e.detail === 'object' && e.detail.avatarUrl) {
				      // 正常情况
				      this.updateAvatar(e.detail.avatarUrl)
				    } else {
				      throw new Error('非标准返回格式')
				    }
				  } catch (err) {
				    console.error('获取头像失败:', err)
				    
				    // 降级方案
				    wx.showModal({
				      title: '提示',
				      content: '获取头像失败，是否尝试从相册选择？',
				      success: (res) => {
				        if (res.confirm) {
				          wx.chooseImage({
				            count: 1,
				            success: (res) => {
				              this.updateAvatar(res.tempFilePaths[0])
				            }
				          })
				        }
				      }
				    })
				}
		    },
		  updateAvatar(tempFilePath) {
			  const that = this
			  var url = app.util.url('Common/upload');
			  wx.uploadFile({
			  	url: url,
			  	filePath: tempFilePath,
			  	name: 'file',
			  	formData: {
			  		'path': tempFilePath
			  	},
			  	success: function (ret) {
			  		ret.data = JSON.parse(ret.data);
			  		console.log(ret.data);
			  
			  		if (ret.data.code!=1){
			  			wx.showModal({
			  				title: '头像上传失败',
			  				content: ret.data.message,
			  				showCancel:false,
			  				success(res) {
			  					that.setData({
			  						"userInfo.avatarUrl": ''
			  					});
			  				}
			  			});
			  		}else{
			  			that.setData({
			  				'userInfo.avatarUrl': ret.data.data.url
			  			});
			  		}
			  	}
			  });
		    
		  },
		    // 获取用户昵称
		  // 昵称输入回调
		    onNickNameInput: function(e) {
		      this.setData({
		        'userInfo.nickName': e.detail.value
		      });
		    },
		    // 获取手机号
		    handleGetPhone(e) {
				const self = this
				console.log(e.detail)
		      if (e.detail.code) {
				  app.util.request({
					  url: 'User/decodePhone',
					  data: {
						code: e.detail.code,
						encryptedData:e.detail.encryptedData,
						iv:e.detail.iv
					  },
					  success: (res) => {
						if (res.data.data.success) {
						  self.setData({
							'userInfo.phone': res.data.data.phoneNumber
						  })
						  wx.showToast({ title: '手机号获取成功' })
						}
					  }
				  })
		      } else {
		        wx.showToast({ title: '获取手机号失败', icon: 'none' })
		      }
		    },
			handleSubmit() {
				const self = this
				if (!this.data.userInfo.avatarUrl || !this.data.userInfo.phone || !this.data.userInfo.nickName) {
					wx.showToast({ title: '请先完善信息', icon: 'none' })
					return
				}
				if(self.data.isSelf){
					//如果是本人  则提示订阅
					let tempId=['kd_vCXBL7Xww9IUkdYCzAwcaiuUzScrjeXh-GGTvGsM','BGzUIeFJ3Hc4pN7_ODFKTz9IxvfAWYsPffIReTKB88s','mAWKv07qdcbyLfg_g50igDKqDz13r6ZuaUH58ctJ1HU'];
					wx.requestSubscribeMessage({
					  tmplIds: tempId,
					  success (res) {
						  // 可以根据每个模板的订阅结果进行处理
							  tempId.forEach(templateId => {
								  console.log(res[templateId])
								if (res[templateId] === 'accept') {
								  console.log(`模板${templateId}订阅成功`)
								  // 可以记录用户已订阅的模板
								} else {
								  console.log(`模板${templateId}订阅失败或被拒绝`)
								  wx.showModal({
								  	title: '温馨提示',
								  	content: "您已关闭消息推送，如需要消息推送服务，请点击确定跳转设置页面打开授权后再次尝试。",
								  	success: function(modal) {
								  		if (modal.confirm) { // 点击确定
								  			wx.openSetting({ withSubscriptions: true })
								  		}
								  	}
								  })
								}
							  })
					   },
					   fail(err) { 
								 console.log(err)
								 if (err.errCode == '20004') {
								  wx.showModal({
									  title: '温馨提示',
									  content: "您的消息订阅主已关闭，如需复习提醒服务，请点击确定跳转设置页面打开授权后再次尝试。",
									  success: function(modal) {
										  if (modal.confirm) { // 点击确定
											  wx.openSetting({ withSubscriptions: true })
										  }
									  }
								  })
								}
						},
						complete(res) {
						  console.log('complete  调用完成')
						  // 无论取消还是接收都会执行:比如 下单(无论订阅号是取消还是接收都执行)
						app.util.request({
							  url: 'User/profile',
							  data: {
									  m: app.mdName,
									  submit: 'save',
									  avatar:self.data.userInfo.avatarUrl,
									  nickname:self.data.userInfo.nickName
							  },
							  success(res) {
								  app.updateMine(function(mine){
									  self.setData({
										  mine: mine
									  });
									  self.saveInfo()
								  });
							  }
						  });
						  
						}
					})
				}
				
				
			},
});